/**
 * Created by DELL on 2017/5/25.
 *   登录界面
 */

//'use strict';
import React, {Component}from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    PixelRatio,
    TouchableHighlight,
    TouchableOpacity,

} from 'react-native';

import BaseComponent, {base, AppIndictor} from '../../base/Base' ;
// import {Navigator, Tab} from "../../base/Navigation";


//变量区域

//引入 图片
var url = require('../../imgs/main/bg_login.jpg');//相对 路径

let {
    N002_USERS$_IS_EXIST,//验证手机号是否已存在
    N003_USERS_GENERATE_CODE,//获取验证码
    LOGIN_1004,//登陆
    REGISTER_1005,//注册

} = base.requests;

let {
    KEY_PHONE,
    KEY_IS_LOGIN,
    SECONDS_MILL_10,
    USER_INFO,
} = base.fields;

export default class Login extends BaseComponent {
    //noinspection JSAnnotator
    mixins: [base.TimerMixin]

    constructor(props) {
        super(props);
        this.state = {
            phone: "",
            code: "",
            secondsElapsed: SECONDS_MILL_10,//倒计时 数字
            showIndictor: false,//显示加载进度框
            isLogined: false,//是否登陆进入主页面
            phoneIsExist: true,//手机号是否在盈家已注册
        }

    };

    //渲染之前 初始化数据
    componentWillMount() {

        base.Store.get(KEY_PHONE)
            .then(phone => {
                this.setState({phone: phone})
            });
    };

    //计时器
    tick() {

        this.interval = base.TimerMixin.setInterval(() => {
            let pre = this.state.secondsElapsed - 1;
            if (pre <= 0) {
                this.setState({
                    secondsElapsed: SECONDS_MILL_10,//初始倒计时 时间
                });

                base.TimerMixin.clearInterval(this.interval);
            } else {
                this.setState({
                    secondsElapsed: pre,
                });

            }

        }, 1000);


    };


    //吐司
    toast_show(content) {
        base.toastShort(content);
    }


    /**
     *  获取验证码
     **/
    getCode() {
        //防止 重复点击
        if (this.state.secondsElapsed !== SECONDS_MILL_10) {
            return;
        }
        var phone = this.state.phone;
        if (!this.checkPhone(phone)) {

            base.toastShort("请输入正确的手机号码");
            return;
        }
        this.setState({showIndictor: true})
        //验证手机号是否已是盈家用户
        base.network.getUipData(N002_USERS$_IS_EXIST, {'cellphone': phone},
            (successData) => {
                if (successData.results != 1) {
                    this.setState({phoneIsExist: false})
                }
                //获取验证码
                base.network.getUipData(N003_USERS_GENERATE_CODE, {'cellphone': phone},
                    (successData) => {
                        this.tick();
                        //保存手机号
                        base.Store.save(KEY_PHONE, phone);
                        this.setState({showIndictor: false})
                    },
                    (error) => {
                        base.toastShort(error);
                        this.setState({showIndictor: false})
                    });

            },
            (error) => {
                base.toastShort(error);
                this.setState({showIndictor: false})
            });



    };

    /**
     *  登录
     **/
    login() {
        var phone = this.state.phone;
        var code = this.state.code;
        if (!this.checkPhone(phone)) {
            base.toastShort("请输入正确的手机号码");
            return;
        }
        if (!this.checkCode(code)) {
            base.toastShort("验证码为6位数字");
            return;
        }

        let params = {};
        params.phone = phone;
        params.verifyCode = code;
        params.platform = base.device.isAndroid() ? "Android" : "Ios";

        if(this.state.phoneIsExist){
            this._goToLogin(params);
        }else {
            this._goToReginster(params);
        }




    };
    //注册
    _goToReginster(params){
        params.gender='1';
        params.checkCode='1';
        params.nickName=params.phone;
        this.setState({showIndictor: true})
        base.network.getUipData(REGISTER_1005, params,
            (successData) => {
                //登陆状态
                base.Store.save(KEY_IS_LOGIN, true)
                    .then(() => base.Store.save(USER_INFO, successData))

                //保存手机号
                base.Store.save(KEY_PHONE, this.state.phone);
                this.setState({showIndictor: false})
                //跳转 主页
                this.gotoMain();
            },
            (error) => {
                base.toastShort('注册失败：' + error);
                this.setState({showIndictor: false})
            });
    }

    //登陆
    _goToLogin(params){
        this.setState({showIndictor: true})
        base.network.getUipData(LOGIN_1004, params,
            (successData) => {

                //登陆状态
                base.Store.save(KEY_IS_LOGIN, true)
                    .then(() => base.Store.save(USER_INFO, successData))

                //保存手机号
                base.Store.save(KEY_PHONE, this.state.phone);
                this.setState({showIndictor: false})
                //跳转 主页
                this.gotoMain();
            },
            (error) => {
                base.toastShort('登录失败：' + error);
                this.setState({showIndictor: false})
            });
    }


    checkPhone(phone) {
        return phone && phone.length === 11;
    };

    checkCode(code) {
        return code && code.length === 6;
    };

    //TODO 235 行 测试阶段 直接跳往 主页，正式时 gotoMain --> login
    render() {
        let getCode_text = this.state.secondsElapsed == SECONDS_MILL_10 ? '获取验证码' : (this.state.secondsElapsed + '秒后重试');

        return (
            <View style={styles.container}>
                <AppIndictor
                    modalVisible={this.state.showIndictor}
                    size={'large'}
                    color={'#ff6138'}
                />


                <Image style={styles.style_login_image} source={ url }>

                    <Text style={[styles.title, {marginTop: 10, width: 80}]}>用户登陆</Text>

                    <View style={[styles.inputRow, {marginTop: 40}]}>
                        <Text style={styles.label}>手机号</Text>
                        <TextInput
                            keyboardType='numeric'
                            clearButtonMode='while-editing'
                            style={styles.input}
                            placeholder="请输入11位手机号"
                            onChangeText={(text) => this.setState({phone: text})}
                            value={this.state.phone}/>
                    </View>


                    <View style={styles.inputRow}>
                        <Text style={styles.label}>验证码</Text>
                        <TextInput
                            keyboardType='numeric'
                            clearButtonMode='while-editing'
                            style={styles.input}
                            placeholder="请输入6位数字"
                            onChangeText={(text) => {
                                return this.setState({code: text});
                            }}
                            value={this.state.code}/>

                        <TouchableOpacity style={[styles.btn, {paddingLeft: 15, paddingRight: 15}]}
                                          underlayColor='#0057a84a'
                                          onPress={this.getCode.bind(this)} ref='codeText'>
                            <Text style={{color: '#0ff', fontSize: 10}}>{getCode_text}</Text>
                        </TouchableOpacity>


                    </View>


                    <TouchableOpacity style={[styles.btn, styles.marginTop30]} onPress={this.login.bind(this)}>
                        <Text style={{color: '#fff', fontSize: 14}}>登录</Text>
                    </TouchableOpacity>

                    <Text style={{color:'#fff',fontSize:10,marginTop:20}}>提示：若未注册，系统将自动为你注册为会员</Text>

                </Image>

            </View>


        );
    }

    //上个页面 传递this ,刷新上个页面
    gotoMain() {

        this.props.root.setState({
            logined:true
        });


    }

}

const styles = StyleSheet.create({
    //总样式
    container: {
        flex: 1,
        flexDirection: "column",
        justifyContent: "flex-start",
        alignItems: "center",

    },
    //背景样式
    style_login_image: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 50,
        flexDirection: 'column',
    },
    loginform: {
        // flex:2,
        flexDirection: 'row',
        justifyContent: 'center',
        backgroundColor: '#00000000',
        paddingLeft: 40,
        paddingRight: 40,
    },
    transparent: {
        backgroundColor: '#00000000',
    },
    title: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        color: '#ffffff',
        fontSize: 20,
        textAlign: 'center',
    },
    action: {
        height: 50,
    },
    marginleft10: {
        marginLeft: 10,
    },
    marginTop20: {
        marginTop: 20,
    },
    marginTop30: {
        marginTop: 30,
    },
    marginRight10: {
        marginRight: 10,
    },

    inputRow: {
        backgroundColor: '#00000000',
        flexDirection: 'row',
        justifyContent: 'center',
        width: 400,
        paddingLeft: 20,
        paddingRight: 20,
        marginTop: 5,
    },
    input: {
        height: 50,
        borderColor: '#ccc',
        color: '#fff',
        flex: 10,
        // width:150,
        fontSize: 14,
    },
    label: {
        //flex:1,
        width: 80,
        fontSize: 16,
        color: '#ffffff',
        marginTop: 15,
    },
    btn: {
        height: 44,
        //display:'flex',
        paddingRight: 50,
        paddingLeft: 50,
        backgroundColor: '#4d796e',
        justifyContent: 'center',
        // alignItems:'center',
        borderRadius: 10,
        borderWidth: 1,
        borderColor: '#ffffff',
    }

});



